package com.cby.library.tool.ui;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;


/**
 * @author ChenBaoyang
 * @description: ViewHelper
 * @date 2021/10/15 16:42
 */
public class ModeHelper {

    public static final String[] MODE_NAMES = new String[]{
            "测试环境",
            "模线上环境"
    };

    public static final Integer[] MODE = new Integer[]{
            0,
            1
    };

    private Context context;

    private SharedPreferences mSp;

    private static ModeHelper sInstance;

    private ModeHelper(Context context){
        this.context = context.getApplicationContext();
        mSp = context.getSharedPreferences("environment", Context.MODE_PRIVATE);
    }

    public static ModeHelper getInstance(Context context) {
        if(sInstance == null) {
            sInstance = new ModeHelper(context.getApplicationContext());
        }
        return sInstance;
    }

    public void initModeSpinner(Spinner spinner) {
        if(spinner == null) {
            return;
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, MODE_NAMES);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                Log.d("m3839", "Set environment as " + MODE_NAMES[pos]);
                saveMode(pos);
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
            }
        });

        // 这里设置默认方向为横屏，SDK内部的默认方向也是
        spinner.setSelection(mSp.getInt("mode", 0));
    }



    private void saveMode(int pos) {
        mSp.edit().putInt("mode", pos).commit();
    }

    public int getMode() {
        int pos = mSp.getInt("mode", 0);
        if (pos < 0 || pos >= MODE.length) {
            pos = 0;
        }
        return MODE[pos];
    }
}
